<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminUser\Action\Admin\Level;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Contract\AdminUserLevelContract;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;

/**
 * 代理等级- 创建提交.
 *
 * Class Store.
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var AdminUserLevelContract
     */
    protected $adminUserLevelService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/admin/adminUser/level/store", methods="post")
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $params = [
            'name' => $this->request->input('name'),
            'order' => $this->request->input('order'),
            'price_rule' => Json::encode($this->request->input('priceRule')),
            'remark' => $this->request->input('remark', ''),
            'status' => $this->request->input('status', 1),
            'created_at' => date('Y-m-d H:i:s'),
        ];

        if (! empty($this->adminUserLevelService->getAdminUserLevelByName($params['name']))) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '代理等级已存在，请重新创建');
        }
        $this->handleParams($params);
        // 数据操作
        Db::beginTransaction();
        try {
            $this->adminUserLevelService->createAdminUserLevel($params);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '代理等级创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '代理等级创建失败');
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'name' => 'required | string | min:1 | bail',
            'order' => 'required | int | bail',
            'priceRule' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'name.required' => '等级名称 必填',
            'name.string' => '等级名称 必需为字符串',
            'name.min' => '等级名称 字符串长度不可小于1',
            'order.required' => '排序 必填',
            'order.integer' => '排序 必需为整数',
            'priceRule.required' => '扣币规则 必填',
        ];
    }

    private function handleParams(array $params): void
    {
        $priceRule = Json::decode($params['price_rule']);
        if ($priceRule['type'] === 1) {
            if ((int) $priceRule['discount'] <= 0 || (int) $priceRule['discount'] > 10) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '统一折扣必须大于0小于等于10');
            }
        }
    }
}
